package kxfang.com.food.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.android.material.tabs.TabLayoutMediator;
import com.zhpan.bannerview.constants.PageStyle;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import kxfang.com.base.activity.MvvmBaseActivity;
import kxfang.com.base.utils.GsonUtils;
import kxfang.com.common.adapter.NetBannerProvider;
import kxfang.com.common.bean.BannerModel;
import kxfang.com.common.bean.GoodsListModel;
import kxfang.com.common.bean.LifeClassModel;
import kxfang.com.common.bean.LifeModel;
import kxfang.com.common.config.HttpConfig;
import kxfang.com.common.constant.Constant;
import kxfang.com.common.dialog.MessageDialog;
import kxfang.com.common.parameter.BannerPar;
import kxfang.com.common.parameter.CommonPar;
import kxfang.com.common.parameter.StorePar;
import kxfang.com.common.router.RoutHub;
import kxfang.com.common.utils.HawkUtil;
import kxfang.com.common.utils.StatusBarUtil;
import kxfang.com.common.views.AnimAction;
import kxfang.com.common.views.BaseDialog;

import kxfang.com.food.R;
import kxfang.com.food.adapter.LabelFlexBoxAdapter;
import kxfang.com.food.adapter.LifeClassAdapter;
import kxfang.com.common.bean.TopListModel;
import kxfang.com.food.databinding.FoodMainLayoutBinding;
import kxfang.com.food.databinding.FoodVipItemBinding;
import kxfang.com.food.ui.fragment.HCFragment;
import kxfang.com.food.ui.fragment.SJFragment;
import kxfang.com.food.viewModel.FoodMainViewModel;
import kxfang.com.food.views.ObservableScrollView;
import kxfang.com.http.EasyHttp;
import kxfang.com.http.callback.SimpleCallBack;
import kxfang.com.http.exception.ApiException;

/**
 * Created by ZJ
 * on 2019-12-11
 * Class Content 生活服务类
 */
@Route(path = RoutHub.FOOD_SQUARE)
public class LifeServiceActivity extends MvvmBaseActivity<FoodMainLayoutBinding, FoodMainViewModel>
        implements ObservableScrollView.ScrollViewListener {
    String[] title = {"推荐商家", "发现好菜"};
    private Context context;
    private BaseQuickAdapter<GoodsListModel, BaseViewHolder> adapter;
    //ViewPage选项卡页面集合
    private List<Fragment> mFragmentList = new ArrayList<>();
    String storeID;//表示是我们平台 和订单号
    private Intent intent = new Intent();
    private LifeClassAdapter lifeClassAdapter;
    private StorePar par = new StorePar();
    private LabelFlexBoxAdapter labelFlexBoxAdapter;

    public double latitude = 0, longitude = 0;
    private LocationManager lm;//【位置管理】
    private boolean ok;

    private TabLayoutMediator mediator;
    private int activeColor = Color.parseColor("#FE2947");
    private int normalColor = Color.parseColor("#333333");

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setTopActivityView(this, viewDataBinding.topView, R.color.common_color_tran);
        context = this;
        getBanner();
        getLifeClass();
        thisClick();
        initLabelView();
        initPager();
        if (HawkUtil.get("HomeAddress") != null) {
            boolean isaddress = HawkUtil.get("HomeAddress");
            if (isaddress) {
                getLocation();
            } else {
                setDialog();
            }
        } else {
            setDialog();
        }
    }

    private void initLabelView() {
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(context);
        layoutManager.setFlexWrap(FlexWrap.WRAP); //设置是否换行
        layoutManager.setFlexDirection(FlexDirection.ROW); // 设置主轴排列方式
        layoutManager.setAlignItems(AlignItems.STRETCH);
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);
        viewDataBinding.labelRecycleView.setLayoutManager(layoutManager);
        labelFlexBoxAdapter = new LabelFlexBoxAdapter();
        viewDataBinding.labelRecycleView.setAdapter(labelFlexBoxAdapter);
        labelFlexBoxAdapter.setOnItemClickListener((adapter, v, p) -> {
            TopListModel topListModel = labelFlexBoxAdapter.getData().get(p);
            if (topListModel.getCType() == 1) {
                //商家
//                Intent intent = new Intent(this, HomeStoreDetailFragment.class);
//                intent.putExtra("id", topListModel.getID());
//                startActivity(intent);
            } else {
                //商品
//                Intent intent = new Intent(context, StoreWebViewActivity.class);
//                intent.putExtra("id", topListModel.getID());
//                context.startActivity(intent);
            }
        });

    }

    /**
     * 定位
     */
    public void getLocation() {
        lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (ok) {//开了定位服务
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                // 没有权限，申请权限。
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 200);
            } else {
                // 有权限了，去放肆吧。
                initLocationOption();
            }
        } else {
            Toast.makeText(this, "系统检测到未开启GPS定位服务", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 1315);
        }
    }

    private void setDialog() {
        new MessageDialog.Builder(this)
                .setTitle("提示")
                .setMessage("当前页面需要获取您的位置信息")
                .setAnimStyle(AnimAction.IOS)
                .setAutoDismiss(true)
                .setListener(new MessageDialog.OnListener() {
                    @Override
                    public void onConfirm(BaseDialog dialog) {
                        HawkUtil.put("HomeAddress", true);
                        getLocation();
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                        HawkUtil.put("HomeAddress", false);
                        initData();
                    }
                }).show();
    }

    /**
     * 初始化定位参数配置
     */

    private void initLocationOption() {

//        LocationHelper
//                .getInstance()
//                .init(this)
//                .isNeedRefresh(false)
//                .setLocationListener((location, isSuccess) -> {
//                    //定位成功回调信息，设置相关消息
//                    latitude = location.getLatitude();//获取纬度
//                    longitude = location.getLongitude();//获取经度
//                    Hawk.put("lat", latitude);
//                    Hawk.put("lng", longitude);
//                    par.setLat(latitude);
//                    par.setLng(longitude);
//                    initData();
//                })
//                .startLocate();
    }

    //设置数据到界面
    private void setView(LifeModel model) {
        storeID = model.getVipbusinessList().get(0).getID();
        labelFlexBoxAdapter.setNewData(model.getTopList());
        //设置中间推荐商家
        Glide.with(this)
                .load(Constant.PHOTO_SERVER_URL.concat(model.getVipbusinessList().get(0).getLogo()))
                .into(viewDataBinding.vipStoreImg);
        viewDataBinding.vipStoreName.setText(model.getVipbusinessList().get(0).getStoreName());
        if (!TextUtils.isEmpty(model.getVipbusinessList().get(0).getEvaluateStr())) {
            viewDataBinding.reimai.setText(model.getVipbusinessList().get(0).getEvaluateStr());
        } else {
            viewDataBinding.reimai.setVisibility(View.INVISIBLE);
        }
        if (model.getVipbusinessList().get(0).getGoodsList() != null
                && model.getVipbusinessList().get(0).getGoodsList().size() != 0) {
            viewDataBinding.ratingBar.setRating(model.getVipbusinessList().get(0).getGoodsList().get(0).getStarNum());
        }
//        viewDataBinding.vipStoreName.setTextColor(getResources().getColor(R.color.white_color));
        if (!TextUtils.isEmpty(model.getVipbusinessList().get(0).getLabel())) {
            String[] str = new String[0];
            if (model.getVipbusinessList() != null && model.getVipbusinessList().get(0).getLabel() != null) {
                str = model.getVipbusinessList().get(0).getLabel().split(",");
            }
            setLabel(str);
        }
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        viewDataBinding.vipRcView.setLayoutManager(linearLayoutManager);
        adapter = new BaseQuickAdapter<GoodsListModel, BaseViewHolder>(R.layout.food_vip_item,model.getVipbusinessList().get(0).getGoodsList()) {

            @Override
            protected void onItemViewHolderCreated(@NotNull BaseViewHolder viewHolder, int viewType) {
                DataBindingUtil.bind(viewHolder.itemView);
            }

            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, @Nullable GoodsListModel goodsListModel) {
                if (goodsListModel == null){
                    return;
                }
                FoodVipItemBinding binding = baseViewHolder.getBinding();
                if (binding != null){
                    binding.setModel(goodsListModel);
                }
            }
        };
        viewDataBinding.vipRcView.setNestedScrollingEnabled(false);
        viewDataBinding.vipRcView.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter, v, postion) -> {
//            Intent intent = new Intent(LifeServiceActivity.this, StoreWebViewActivity.class);
//            intent.putExtra("id", model.getVipbusinessList().get(0).getGoodsList().get(postion).getID());
//            startActivity(intent);
        });
    }

    public void initPager(){
        SJFragment sjFragment = new SJFragment();
        sjFragment.setLat(latitude, longitude);
        HCFragment hcFragment = new HCFragment();
        sjFragment.setLat(latitude, longitude);
        mFragmentList.add(sjFragment);
        mFragmentList.add(hcFragment);
        viewDataBinding.viewpager.setOffscreenPageLimit(ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT);
        viewDataBinding.viewpager.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) {
            @Override
            public int getItemCount() {
                return mFragmentList.size();
            }

            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return mFragmentList.get(position);
            }
        });
        mediator = new TabLayoutMediator(viewDataBinding.tabLayout, viewDataBinding.viewpager
                , (tab, position) -> {
            //这里可以自定义TabView
            TextView tabView = new TextView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, 0, 1.0f);

            int[][] states = new int[2][];
            states[0] = new int[]{android.R.attr.state_selected};
            states[1] = new int[]{};

            int[] colors = new int[]{activeColor, normalColor};
            ColorStateList colorStateList = new ColorStateList(states, colors);
            tabView.setText(title[position]);
            tabView.setTextSize(15);
            tabView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            tabView.setTextColor(colorStateList);

            tab.setCustomView(tabView);
        });
        mediator.attach();
    }

    private void setLabel(String[] fStr) {
        //福利待遇
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        for (int j = 0; j < fStr.length; j++) {
            if (j > 3) {
                break;
            }
            TextView textView = new TextView(context);
            textView.setText(fStr[j]);
            textView.setTextColor(context.getResources().getColor(R.color.common_color_2947));
            textView.setBackgroundResource(R.drawable.shape_manjian_red_bg);
            textView.setPadding(10, 5, 10, 5);
            textView.setTextSize(9);
            lp.setMargins(0, 0, ((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, context.getResources().getDisplayMetrics())), 0);
            textView.setLayoutParams(lp);
            viewDataBinding.labelLayout.addView(textView);
        }
    }

    //获取banner
    private void getBanner() {
        BannerPar par = new BannerPar();
        par.setVtype(7);
        EasyHttp.post(HttpConfig.getBanner)
                .cacheKey("banner")
                .upJson(GsonUtils.toJson(par))
                .execute(new SimpleCallBack<List<BannerModel.DataBean>>() {
                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onSuccess(List<BannerModel.DataBean> dataBeans) {
                        bannerInit(dataBeans);
                    }
                });
    }

    //设置banner显示
    public void bannerInit(List<BannerModel.DataBean> image) {
        List<String> list = new ArrayList<>();
        for (BannerModel.DataBean temp : image) {
            list.add(Constant.PHOTO_SERVER_URL.concat(temp.getUrl()));
        }
        viewDataBinding.lifeBanner.setHolderCreator(NetBannerProvider::new)
                .setPageStyle(PageStyle.MULTI_PAGE_OVERLAP)
                .create(list);
    }

    //请求数据
    private void initData() {
        EasyHttp.post(HttpConfig.getLifeData)
                .cacheKey(HttpConfig.getLifeData)
                .upJson(GsonUtils.toJson(par))
                .execute(new SimpleCallBack<LifeModel>() {
                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onSuccess(LifeModel lifeModel) {
                        setView(lifeModel);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mediator.detach();
        System.out.println(getPackageName().concat("销毁了------------->"));
    }

    @Override
    protected FoodMainViewModel getViewModel() {
        return new FoodMainViewModel();
    }

    @Override
    protected int getBindingVariable() {
        return 0;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.food_main_layout;
    }

    @Override
    protected void onRetryBtnClick() {

    }

    private void getLifeClass() {
        //美食分类接口
        par.setCtype(3);
        EasyHttp.post(HttpConfig.getFoodClass)
                .cacheKey("class")
                .upJson(GsonUtils.toJson(par))
                .execute(new SimpleCallBack<List<LifeClassModel>>() {
                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onSuccess(List<LifeClassModel> lifeClassModel) {
                        initView(lifeClassModel);
                    }
                });
    }

    //初始化点击事件
    private void thisClick() {
        viewDataBinding.scrollView.setScrollViewListener(this);
        //预约订座
        viewDataBinding.yuDing.setOnClickListener(v -> {
            ToastUtils.showShort("敬请期待");
        });
        //今日特价
        viewDataBinding.todayImg.setOnClickListener(v -> {
            startActivity(new Intent(this, FoodWebActivity.class));
        });
        //必吃榜
        viewDataBinding.mustImg.setOnClickListener(v -> {
            Intent intent = new Intent(this, FoodWebActivity.class);
            intent.putExtra("type", 1);
            startActivity(intent);
        });
        //跳转商家页面
        viewDataBinding.storeLayout.setOnClickListener(v -> {
//            Intent intent = new Intent(this, HomeStoreDetailFragment.class);
//            intent.putExtra("id", storeID);
//            startActivity(intent);
        });
        //返回上一级界面
        viewDataBinding.lifeBack.setOnClickListener(v -> finish());
        //扫一扫
        viewDataBinding.lifeSaoyisao.setOnClickListener(v -> {
//            if (HawkUtil.getUserId() == null) {
//                myShowDialog("您还未登录", LifeServiceActivity.this);
//                return;
//            }
//            intent.setClass(this, MainScanActivity.class);
//            startActivityForResult(intent, REQUEST_CODE);
        });
    }

    //初始化数据
    private void initView(List<LifeClassModel> list) {
//        HomeGridAdapter adapter = new HomeGridAdapter(this, images, text);
        if (list.size() != 0){
            viewDataBinding.gridView.setVisibility(View.VISIBLE);
        }
        lifeClassAdapter = new LifeClassAdapter();
        viewDataBinding.gridView.setLayoutManager(new GridLayoutManager(this,5));
        viewDataBinding.gridView.setAdapter(lifeClassAdapter);
        lifeClassAdapter.setNewData(list);
        lifeClassAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (list.get(position).getClassName().equals("大牌惠吃")) {
                Intent intent = new Intent(LifeServiceActivity.this, FoodWebActivity.class);
                intent.putExtra("type", 2);
                startActivity(intent);
                return;
            }
//            Navigate.push(this, ClassifyDetailFragment.class, 2, list.get(position).getID(), list.get(position).getClassName(), 2);
        });

    }


    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        if (y < 10) {
            viewDataBinding.topLayout.setBackgroundResource(R.color.common_color_tran);
            viewDataBinding.topImg.setImageResource(R.drawable.food_left_title);
            viewDataBinding.lifeBack.setImageResource(R.drawable.common_store_back);
            viewDataBinding.lifeSaoyisao.setImageResource(R.drawable.food_scanner_white);
            StatusBarUtil.setTopActivityView(this, viewDataBinding.topView, R.color.common_color_tran);
        } else {
            viewDataBinding.topLayout.setBackgroundResource(R.color.common_colorWhite);
            viewDataBinding.topImg.setImageResource(R.drawable.food_life_blank_title);
            viewDataBinding.lifeBack.setImageResource(R.drawable.common_store_black_back);
            viewDataBinding.lifeSaoyisao.setImageResource(R.drawable.common_scanner_black);
            StatusBarUtil.setTopActivityView(this, viewDataBinding.topView, R.color.common_colorWhite);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
//        ScanResultUtils.getInstance().resultForScan(requestCode, data, context);
    }

    public void search() {
//        Navigate.push(this, SearchAllFragment.class, Constant.SEARCH_FOOD);
    }
}
